// 2025/11/13
// 二叉树中的最大路径和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    pair<int, int> dfs(TreeNode* root)
    {
        pair<int, int> ans(0, INT_MIN);
        if(root == nullptr)
            return ans;
        auto left = dfs(root->left);
        auto right = dfs(root->right);
        ans.first = root->val + max(0, max(left.first, right.first));
        int sum = root->val + left.first + right.first;
        ans.second = max(max(ans.first, sum), max(left.second, right.second));
        return ans;
    }

    int maxPathSum(TreeNode* root) {
        return dfs(root).second;
    }
};